<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter title="编辑代码生成信息" width="90%" @ok="handleSubmit">
    <Tabs v-model:activeKey="activeKey">
      <TabPane key="1" tab="代码生成信息">
        <BasicForm @register="registerForm" />
      </TabPane>
      <TabPane key="2" tab="字段属性设置" force-render>
        <BasicTable @register="registerTable" @edit-end="handleEditEnd" />
      </TabPane>
      <TabPane key="3" tab="代码预览" force-render>
        <Tabs v-model:activeKey="previewActiveKey">
          <TabPane v-for="item in codes" :key="item.title" :tab="item.title" force-render>
            <pre>{{ item.content }}</pre>
          </TabPane>
        </Tabs>
      </TabPane>
    </Tabs>
  </BasicDrawer>
</template>
<script lang="ts" setup name="UpdateDrawer">
import { ref } from 'vue';
import {
  BasicTable,
  useTable,
} from '/@/components/Table';
import { BasicForm, useForm } from '/@/components/Form/index';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { formSchema, tableFieldcolumns } from './index-option';
import { getGenTableFieldPage, updateGenTable, previewApi } from '/@/api/sys/gen';
import { useMessage } from '/@/hooks/web/useMessage';
import { Tabs, TabPane } from 'ant-design-vue';
import { downloadByData } from '/@/utils/file/download';

const emit = defineEmits(['success']);
const { createMessage } = useMessage();
const activeKey = ref('1');
const previewActiveKey = ref('1');
const tableId = ref();
const tableFields = new Map<String, any>();
const codes = ref();

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  tableFields.clear();
  activeKey.value = '1';
  resetFields();
  tableId.value = data.record.tableId;
  if (data.record.buttonTypes != null && !Array.isArray(data.record.buttonTypes)) {
    data.record.buttonTypes = data.record.buttonTypes.split(',').map(item => parseInt(item));
  } else {
    data.record.buttonTypes = [];
  }
  setFieldsValue({
    ...data.record
  });
  reload();
  previewGen(tableId.value);
});

const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 100,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { lg: 12, md: 24 },
});

const [registerTable, { reload }] = useTable({
  api: getGenTableFieldPage,
  rowKey: 'fieldId',
  columns: tableFieldcolumns,
  striped: false,
  useSearchForm: false,
  showTableSetting: false,
  bordered: true,
  showIndexColumn: true,
  canResize: false,
  immediate: false,
  pagination: { pageSize: 100 },
  beforeFetch: handleBeforeFetch,
});

async function previewGen(tableId: string) {
  const result = await previewApi(tableId);
  codes.value = result.data;
  previewActiveKey.value = result.data[0].title;
}

async function handleSubmit() {
  try {
    const values = await validate();
    setDrawerProps({ confirmLoading: false });
    let fields = new Array<Object>();
    for (let item of tableFields.values()) {
      delete item.submitCbs;
      delete item.validCbs;
      delete item.cancelCbs;
      delete item.editValueRefs;
      fields.push(item);
    }
    const param = { ...values, tableId: tableId.value, tableFields: fields };
    if (param.buttonTypes.length > 0) {
      param.buttonTypes = param.buttonTypes.join(',');
    } else {
      delete param.buttonTypes;
    }
    const res = await updateGenTable(param);
    createMessage.success(res.msg);
    closeDrawer();
    emit('success');
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}

function handleEditEnd({ record }: Recordable) {
  tableFields.set(record.fieldId, record);
  return false;
}

// 表格请求之前，对参数进行处理
function handleBeforeFetch(params) {
  return { ...params, tableId: tableId.value };
}
</script>
